import models from '../../../models'

export default defineEventHandler(async (event: any) => {
  try {
    const query = getQuery(event)
    const where: {
      type?: string;
      regionCode?: string;
      parentId?: number;
      level?: number;
    } = {}
    
    if (query.type) {
      where.type = query.type as string
    }
    
    if (query.regionCode) {
      where.regionCode = query.regionCode as string
    }
    
    if (query.parentId) {
      where.parentId = parseInt(query.parentId as string)
    }
    
    if (query.level === '1') {
      where.level = 1
    }
    
    const organizations = await models.Organization.findAll({
      where,
      include: [
        {
          model: models.Region,
          attributes: ['name', 'code']
        },
        {
          model: models.Organization,
          as: 'parent',
          attributes: ['name', 'code']
        }
      ],
      order: [['code', 'ASC']]
    })
    
    return { organizations }
  } catch (error) {
    throw createError({
      statusCode: 500,
      message: '获取组织列表失败'
    })
  }
}) 